/***
 * 执行云呼call客的工具js
 * */
//var connwsUrl = "ws://113.108.202.235:7771/wbs/browser/connect";
var connwsUrl = cloudCallWs+"/browser/connect";
//var userId = "11";
//userId重复的话,会被认为是同一用户,所有不能外呼
var userId=Math.floor(Math.random()*(999+1));
var machineId = "testCallMachine";
var pageFrom = "11";
var webSocket;
var heartbeatTarget;//心跳任务
var dataId;// 通过dataId 进行交互
var lastMsg="";//用于保存上次发送过得数据 === 用于判断是否重复接收相同信息
var lastCallParameter = "";//上一次呼叫的参数 === 用于判断是否重复外呼操作
var callStatus="";
var token="";//发送webSocket的参数 ---同时也作为外呼的凭证
var toDoCallTime = null;//执行外呼操作的时间
var tryConnCount = 5;//自定义重连次数
var isSendSuccess = false;
var callParameter;



var WebSocketEvent = {
    createEvent: function (dataId,type, value) {
        var wsEvent = {};
        wsEvent.dataId = dataId;
        wsEvent.type = type;
        wsEvent.value = value;
        return wsEvent;
    }
};



//此webSockect 发送外呼操作，保持一个，不然多个监听，会同时触发多次
//用于监听storage
window.top.addEventListener("storage", function(event) {
    switch(event.key){
        case "call"://发起外呼                      
            var callParam = JSON.parse(event.newValue);
            if(callParam!=null){
                callout(JSON.parse(event.newValue));
            }            
            break;
        default:break;
    }
});


/**外呼的方法 */
function callout(jsonObj){    
    //如果发起外呼操作ws是不存在的情况下 === 》 进行连接ws操作
    if(lastCallParameter!=null && lastCallParameter !="" && (lastCallParameter.id==jsonObj.id && lastCallParameter.pageFrom==jsonObj.pageFrom)){
        console.log("======非重拨操作，参数一致，识别为重复发送外呼异常操作 直接返回======");
        return ;
    }
    lastCallParameter = jsonObj;
    isSendSuccess = false;//执行的通话的操作是否发送成功标识 初始化false
    toDoCallTime =new Date();//执行外呼的时间
    call(jsonObj);
}

/**
 * 传递参数
 * mainCallPhone：主叫号码
 * targetCallPhone：被叫号码
 * dataId：通话记录的id
 * showNum：主显号码 (暂不传递)
 * whereFrom:系统来源
 * pageFrom:页面来源
 * machineFrom:机器码
 * mainCallType:谁呼出.经纪人0/客户1
 * commitTo:提交到哪里(线路)
 * createUserId:呼叫经纪id
 * customerName:发起呼叫人的名字
 * mainCallType:谁呼出.经纪人0/客户1
 * */
function call(callParameter){   
    try {              
        console.log("-----进行外呼操作-------");
        isSendSuccess = true;//发送成功
        console.log("callParameter.commitTo========="+callParameter.commitTo);
        webSocket.send(JSON.stringify({
            // msgType: "asrCall2",
            msgType: "CALL",
            mainCallPhone: callParameter.mainCallPhone,
            targetCallPhone: callParameter.targetCallPhone,            
            dataId:callParameter.id,
            whereFrom:11,
            pageFrom:callParameter.pageFrom,
            machineFrom:token,
            mainCallType:callParameter.mainCallType,
            commitTo:callParameter.commitTo,
            createUserId:callParameter.createUserId,
            customerName:callParameter.customerName,
            packageId:"111111111",
            callTaskId:"0",
            city:callParameter.cityId,
			source:'aiCall'
        }));
    }catch (e) {
        console.log("call error");
        console.log(e);
        console.log(e.message);
    }
}



function connWS() {
    try {
        if (webSocket == undefined
            || (webSocket.readyState != WebSocket.OPEN && webSocket.readyState != WebSocket.CONNECTING)) {
            var timestamp = new Date().getTime();//获取当前的时间戳                  
			//连接ws的参数：  source  必填 bl (baoli)、token 必填 (机器码_时间戳)、userId 必填 pageFrom 必填
            var cloudCallUrl = connwsUrl + "?token=" + machineId + "_" + timestamp + "&userId=" + userId+ "&pageFrom=" + pageFrom+"&source=bl";
            token = machineId + "_" + timestamp;
            console.log("---websocket url:"+cloudCallUrl);
            webSocket = new WebSocket(cloudCallUrl);
            webSocket.onopen = function (event) {
                callback(event);
            };
            webSocket.onmessage = function (event) {
                callback(event);								
            };
            webSocket.onclose = function (event) {
                //清除心跳任务
                clearInterval(heartbeatTarget);
                heartbeatTarget = null;
                callback(event);
            };
            webSocket.onerror = function (event) {
                callback(event);
            };
            if (heartbeatTarget == null) {
                heartbeatTarget = setInterval("heartbeat()", 10000);
            }
        }
    }catch (e){
        console.log("创建连接异常"+e.message);
    }
}

//发送ws心跳包
function heartbeat() {
    try {
        webSocket.send(JSON.stringify({
            msgType:"BEAT",
            token:token
        }));
    } catch (e) {
        console.log("call error");
        console.log(e.message);
    }
}


//回调函数
function callback(event){
    console.log(event);
    try{
        switch (event.type) {
            case "open":
                console.log("ws连接已打开");				
				$("#txResult").val($("#txResult").val()+"ws连接已打开\n");     				
                break;
            case "message":                
				$("#txResult").val($("#txResult").val()+"接收到ws信息： " + event.data+"\n");           				
				$("#callBtn").attr("disabled",false);
                var value = event.data;
                var dataObj = JSON.parse(event.data);                
				callbackPC(event.data);		
                break;
            case "error":                 			
				$("#txResult").val($("#txResult").val()+"ws连接异常\n");     								
                break;
            case "close":
				$("#txResult").val($("#txResult").val()+"ws连接关闭\n");     				
                break;
            default:
                break;
        }
    }catch (e){
        console.log("接收处理返回信息的操作异常"+e.message);
    }
}

window.onbeforeunload = function() {    
    try{
         return "重新加载或关闭窗体,会导致正在外呼的通话状态无法返回,您确定要重新加载窗体?";
    }catch (e){
        console.log("操作异常"+e.message);
    }
};

